﻿using FanaticRock.MediaSource.AutoBuilder;
using FanaticRock.MediaSource.BilibiliAPI.Extensions;
using FanaticRock.MediaSource.BilibiliAPI.Helpers;
using FanaticRock.MediaSource.BilibiliAPI.RequestVo.WebInterface;
using FanaticRock.MediaSource.BilibiliAPI.ResponseDto.WebInterface;
using System.Runtime.CompilerServices;
using System.Text.Json;

namespace FanaticRock.MediaSource.BilibiliAPI.API.WebInterface
{
    [HttpRequestInclude]
    public class View
    {
        [MethodInclude]
        public static async Task<ViewResponseDto> InvokeByAid(long aid)
        {
            return await Invoke(ViewRequestVo.CreateFromAid(aid));
        }

        [MethodInclude]
        public static async Task<ViewResponseDto> InvokeByBvid(string bvid)
        {
            return await Invoke(ViewRequestVo.CreateFromBvid(bvid));
        }

        [MethodInclude]
        public static async Task<ViewResponseDto> Invoke(ViewRequestVo vo)
        {
            try
            {
                var httpClient = HttpClientHelper.GetHttpClient();

                using var requestMessage = new HttpRequestMessage(
                    method: HttpMethod.Get,
                    requestUri: $"https://api.bilibili.com/x/web-interface/view?{vo.ToQureyParameter()}");

                //requestMessage.Headers.Referrer = new Uri("wwww.bilibili.com");

                using var responseMessage = await httpClient.SendAsync(requestMessage);
                responseMessage.EnsureSuccessStatusCode();

                using var stream = await responseMessage.Content.ReadAsStreamAsync();
                var resultDto = await JsonSerializer.DeserializeAsync<ViewResponseDto>(stream);
                //throw new Exception();
                return resultDto;
            }
            catch (Exception ex)
            {
                return new ViewResponseDto()
                {
                    Code = Enums.CodeEnum.RequestError,
                    Message = ex.ToString(),

                };
            }
        }


    }
}
